<?php

namespace app\yperp\logic;

use think\queue\Job;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Client as GuzzleHttpClient;
use think\Db as ThinkDb;
use think\facade\Cache;
use think\Queue;

class SupplierAsync
{
    private static $instance;
    protected  $token;
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    function run($is_sync_goods = false)
    {
        $client = new GuzzleHttpClient([
            'verify' => env('root_path') . 'application\yperp\common\cacert.pem',
        ]);
        // dump(module_config('yperp.jst_token'));
        try {
            $response = $client->request('GET', 'https://gyl.scm121.com/api/drp/mySupplier/queryMySupplier', [
                'query' => [
                    'sort' => 'cdp.APPLY_TIME desc, cdp.DAYS_ORDER_QTY desc, cdp.SHELVES_QTY desc',
                    'status' => '2',
                    'pageNum' => '1',
                    'pageSize' => '2000',
                    // 'vagueSearch'=>'书'
                ],
                'headers' => [
                    'authorization' => module_config('yperp.jst_token'),
                ]
            ]);
            $data = $response->getBody()->getContents();
            // dump($data);
            $data = json_decode($data, true);

            if ($data['success'] == true) {
                foreach ($data['data'] as $value) {
                    $items['coId'] = $value['coId'];
                    $items['coName'] = $value['coName'];
                    $items['channelId'] = $value['channelId'];
                    $items['partnerId'] = $value['partnerId'];
                    $items['supplierId'] = $value['supplierId'];
                    $items['supplierName'] = $value['supplierName'];
                    $items['supplierLogo'] = $value['supplierLogo'];
                    $items['supplierTagNames'] = $value['supplierTagNames'];
                    $bool = ThinkDb::name('yperp_supplier_corp')->where(['supplierId' => $items['supplierId']])->value('supplierId');
                    if ($bool) {
                        $res =  ThinkDb::name('yperp_supplier_corp')->where(['supplierId' => $items['supplierId']])->update($items);
                    } else {
                        $res =   ThinkDb::name('yperp_supplier_corp')->where(['supplierId' => $items['supplierId']])->insert($items);
                    }
                    // dump($value['supplierId'] . '更新完成');
                    if ($is_sync_goods) {
                        Queue::push(GoodsAsync::class, $items['supplierId']);
                    }
                }
            }
        } catch (GuzzleException $e) {
            return $e->getMessage();
        }
    }
}
